package com.mzy.linear_struct.subject;

/**
 * @Author: codermzy
 * @Date: 2024/04/25/下午5:03
 * @Description:
 */
public class 两个线程交替打印Synchronized {

    public static final Object lock = new Object();
    public static boolean printNumber = false;


    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            synchronized (lock) {
                for (char i = 'A'; i <= 'C'; i++) {
                    try {
                        while (!printNumber) {
                            lock.wait();
                        }

                        System.out.println(i);
                        printNumber = false;
                        lock.notifyAll();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }


                }
            }


        }, "t1");

        Thread t2 = new Thread(() -> {

            synchronized (lock) {
                for (int i = 1; i <= 3; i++) {
                    try {
                        while (printNumber) {
                            lock.wait();
                        }
                        System.out.println(i);
                        printNumber = true;
                        lock.notifyAll();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }

                }
            }

        }, "t2");

        t1.start();
        // TimeUnit.SECONDS.sleep(1);
        t2.start();
    }
}
